import BusinessError from '@/core/framework/error/BusinessError'
import responseUtils from '@/core/utils/responseUtils'
import { R } from '@/components/axios/interface'

export default class PromiseResponseHelper<TR> {
	private promiseResponse: Promise<R<TR>>

	constructor(promiseResponse: Promise<R<TR>>) {
		this.promiseResponse = promiseResponse
	}

	convert = <D>(convertFn: (res: R<TR>) => Promise<R<D>>): PromiseResponseHelper<D> => {
		const convertPromise = this.promiseResponse.then(convertFn)
		return new PromiseResponseHelper<D>(convertPromise)
	}
	ifSuccessConvert = <D>(successConvertFn: (res: R<TR>) => Promise<R<D>>): PromiseResponseHelper<D> => {
		const promise = this.promiseResponse.then(res => {
			if (responseUtils.isFailure(res)) {
				return {
					code: res.code,
					message: res.message,
				} as R<D>
			}
			return successConvertFn(res)
		})
		return new PromiseResponseHelper<D>(promise)
	}
	check = async (): Promise<TR> => {
		return this.promiseResponse.then(res => {
			if (responseUtils.isFailure(res)) {
				throw new BusinessError(res.code, res.message)
			}
			return res.data
		})
	}
	origin = async (): Promise<R<TR>> => {
		return this.promiseResponse
	}
}
